﻿Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Form1
    Function MultiReplace(input As String, ParamArray replacements() As String) As String
        Dim result As String = input
        For i = 0 To replacements.Count - 1 Step 2
            result = result.Replace(replacements(i), replacements(i + 1))
        Next
        Return result
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim files() As String = Directory.GetFiles(TextBox1.Text)
        Dim extensionList As List(Of String) = TextBox2.Text.Split(",").Select(Function(ext) ext.Trim().ToLower()).ToList
        Dim re As New Regex(TextBox3.Text, RegexOptions.Singleline) 'TextBox3.Text="\n"
        ' 获取用户选择的编码
        Dim selectedEncoding As String = ComboBox1.SelectedItem.ToString().Split(" - ")(0)
        Dim encoding As Encoding = Encoding.GetEncoding(selectedEncoding)
        For Each fileName In files
            If extensionList.Contains(Path.GetExtension(fileName).ToLower()) Then
                Dim fullPath As String = Path.Combine(TextBox1.Text, fileName)
                Dim content As String = File.ReadAllText(fullPath, encoding)
                Dim userInput As String = MultiReplace(TextBox4.Text, "\r", vbCr, "\n", vbLf)
                content = re.Replace(content, userInput) 'TextBox4.Text="\r\n"
                File.WriteAllText(fullPath, content, encoding)
            End If
        Next
        MsgBox("完成！")
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' 获取所有可用的编码
        Dim encodings As EncodingInfo() = Encoding.GetEncodings()

        ' 清空 ComboBox
        ComboBox1.Items.Clear()

        Dim gbIndex As Integer = 0

        ' 添加每个编码的名称和描述到 ComboBox
        For Each encodingInfo As EncodingInfo In encodings
            ComboBox1.Items.Add(encodingInfo.Name & " - " & encodingInfo.DisplayName)
            If encodingInfo.Name = "gb2312" Then
                gbIndex = ComboBox1.Items.Count - 1
            ElseIf gbIndex = 0 AndAlso encodingInfo.Name = "utf-8" Then
                gbIndex = ComboBox1.Items.Count - 1
            End If
        Next

        ' 设置默认选中项
        If ComboBox1.Items.Count > 0 Then
            ComboBox1.SelectedIndex = gbIndex
        End If
    End Sub
End Class
